package mywork

import java.util.UUID
import scala.concurrent.duration._

import akka.actor.{Actor, ActorLogging, ActorRef}

/**
  * Created by shichen on 2017/8/1.
  */
object MyProducer {
  case object Tick
}

class MyProducer(frontend: ActorRef) extends Actor with ActorLogging {
  import MyProducer._
  import context.dispatcher

  def scheduler = context.system.scheduler
  def nextId: String = UUID.randomUUID().toString

  var n = 0

  override def receive: Receive = {
    case Tick =>
      n += 1
      log.info("produce work {}",n)
      val work = MyWork(nextId,n)
      frontend ! work
      context.become(waitAccepted(work),discardOld = false)
  }

  def waitAccepted(work: MyWork): Receive = {
    case MyFrontend.Ok =>
      context.unbecome()
      scheduler.scheduleOnce(5.seconds,self,Tick)
    case MyFrontend.NotOk =>
      log.warning("work not accepted, retry later")
      scheduler.scheduleOnce(5.seconds,frontend,Tick)
  }

  override def preStart(): Unit = {
    scheduler.scheduleOnce(5.seconds,self,Tick)
  }
}